package game.module.mj.processor;

import java.util.List;
import java.util.concurrent.TimeUnit;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import game.HallServer;
import game.common.PlayingRoleMsgProcessor;
import game.entity.PlayingRole;
import game.module.hall.logic.CheatManager;
import game.module.mj.bean.MjRoom;
import game.module.mj.logic.MjDataManager;
import game.module.mj.logic.MjLogic;
import game.module.offline.bean.PlayerOfflineCache;
import game.module.offline.logic.PlayerOfflineManager;
import game.session.SessionManager;
import lion.netty4.message.MyRequestMessage;
import lion.netty4.message.RequestMessageRaw;
import lion.netty4.message.RequestProtoMessage;
import lion.common.MsgCodeAnn;
import lua.LuaMessageLogin.S2ErrorCode;
import lua.LuaMessageMj.C2SMJJoinRoom;
import lua.LuaMessageMj.MJMemberInfo;
import lua.LuaMessageMj.PushMJSPlayerJoin;
import lua.LuaMessageMj.S2CMJJoinRoom;

@MsgCodeAnn(msgcode = C2SMJJoinRoom.id, accessLimit = 500)
public class MjJoinRoomProcessor extends PlayingRoleMsgProcessor {

	private static Logger logger = LoggerFactory.getLogger(MjJoinRoomProcessor.class);

	@Override
	public void process(PlayingRole hero, RequestMessageRaw request) throws Exception {
		// TODO Auto-generated method stub
		C2SMJJoinRoom reqMsg = C2SMJJoinRoom.parse(request);
		String room_id = reqMsg.room_id;
		int playerId = hero.getId();
		logger.info("mj join room,playeyId={},room_id={}", playerId, room_id);
		// 是否在房间
		boolean isInRoom = MjDataManager.getInstance().isPlayerInRoom(playerId);
		if (isInRoom) {
			S2ErrorCode respMsg = new S2ErrorCode(102);
			hero.writeAndFlush(respMsg.build(hero.alloc()));
			return;
		}
		// is fang not exist
		if (!MjDataManager.getInstance().checkRoomExist(room_id)) {
			S2ErrorCode respMsg = new S2ErrorCode(104);
			hero.writeAndFlush(respMsg.build(hero.alloc()));
			return;
		}
		final MjRoom mjRoom = MjDataManager.getInstance().getMjRoom(room_id);
		// 人数满了
		if (mjRoom.getPlayerList().size() >= 4) {
			S2ErrorCode respMsg = new S2ErrorCode(105);
			hero.writeAndFlush(respMsg.build(hero.alloc()));
			return;
		}
		if (CheatManager.getInstance().checkCheatAndJoin(mjRoom.getPrevent_cheat(), mjRoom.getIps(), hero)) {
			return;
		}
		MjLogic.getInstance().addRoomPlayer(playerId, room_id);
		S2CMJJoinRoom respMsg = new S2CMJJoinRoom();
		respMsg.prevent_cheat = mjRoom.getPrevent_cheat();
		respMsg.room_id = room_id;
		respMsg.round_count = mjRoom.getRoundCount();
		respMsg.dapai = mjRoom.getDapai();
		respMsg.typehu = mjRoom.getTypehu();
		respMsg.cost_type = mjRoom.getCost_type();
		respMsg.members = new MJMemberInfo[mjRoom.getPlayerList().size()];
		respMsg.ready = mjRoom.getReadyState();
		List<Integer> playerIdList = mjRoom.getPlayerList();
		int i = 0;
		for (Integer aPlayerId : playerIdList) {
			PlayerOfflineCache poc = PlayerOfflineManager.getInstance().getPlayerOfflineCache(aPlayerId);
			respMsg.members[i++] = new MJMemberInfo(aPlayerId, poc.getHeadimg(), poc.getLevel(), poc.getSex().shortValue(), poc.getName());
		}
		hero.writeAndFlush(respMsg.build(hero.alloc()));
		// data
		MjDataManager.getInstance().addPlayer(playerId, room_id);
		// push
		PushMJSPlayerJoin pushPlayerJoin = new PushMJSPlayerJoin();
		pushPlayerJoin.seat_index = (short) (mjRoom.getPlayerList().size() - 1);
		pushPlayerJoin.member_info = new MJMemberInfo(playerId, hero.getPlayerBean().getHeadimg(), hero.getPlayerBean().getLevel(), hero.getPlayerBean().getSex().shortValue(),
				hero.getPlayerBean().getName());
		for (Integer aPlayerId : playerIdList) {
			if (aPlayerId == playerId) {
				continue;
			}
			PlayingRole pr = SessionManager.getInstance().getPlayer(aPlayerId);
			if (pr != null && pr.isChannelActive()) {
				pr.writeAndFlush(pushPlayerJoin.build(pr.alloc()));
			}
		}
		// delay 2 seconds to start
		// HallServer.executorService.schedule(new Runnable() {
		//
		// @Override
		// public void run() {
		// if (MjRoom.getPlayerList().size() >= 4) {
		// sendRoomStart(MjRoom);
		// }
		// }
		// }, 2, TimeUnit.SECONDS);
	}

	private void sendRoomStart(MjRoom mjRoom) {
		logger.info("mj start battle!");
		String rsLanHost = HallServer.getInstance().getServerConfig().getRsLanHost();
		int rsLanPort = HallServer.getInstance().getServerConfig().getRsLanPort();
		boolean reconnectRet = HallServer.getInstance().getLanClientManager().connect(rsLanHost, rsLanPort);
		if (reconnectRet) {
			HallServer.getInstance().getLanClientManager().sendMjStart2Rs(rsLanHost, rsLanPort, mjRoom);
		} else {
			logger.error("connect 2 roomServer error!rsLanHost={},rsLanPort={}", rsLanHost, rsLanPort);
		}
	}

	@Override
	public void processProto(PlayingRole playingRole, RequestProtoMessage request) throws Exception {
		// TODO Auto-generated method stub

	}

	@Override
	public void processWebsocket(PlayingRole playingRole, MyRequestMessage request) throws Exception {
		// TODO Auto-generated method stub

	}

}
